﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

using Preactor.ObjectModel;

namespace Preactor.ObjectModelExtensions.Entities
{
    public static class ProgressDisplay
    {
        public static void Run<T>(PreactorObjectModel preactorObjectModel, IEnumerable<T> enumerable, Action<PreactorObjectModel, T> action, string title, string message, int windowHandle, bool enableCancel = false)
        {
            preactorObjectModel.Preactor.DisplayStatus(title, message, string.Empty, windowHandle);

            int counter = 1;
            int totalCount = enumerable.Count();

            foreach(var item in enumerable)
            {
                var updateStatus = preactorObjectModel.Preactor.UpdateStatus(counter, totalCount);

                if(enableCancel && updateStatus == ProgressBarStatus.UserCancelled)
                {
                    break;
                }

                counter++;

                action(preactorObjectModel, item);
            };

            preactorObjectModel.Preactor.DestroyStatus();
        }

        public static void Run<T>(PreactorObjectModel preactorObjectModel, IEnumerable<T> enumerable, Action<T> action, string title, string message, bool enableCancel=false)
        {
            preactorObjectModel.Preactor.DisplayStatus(title, message);

            int counter = 1;
            int totalCount = enumerable.Count();

            foreach (var item in enumerable)
            {
                var updateStatus = preactorObjectModel.Preactor.UpdateStatus(counter, totalCount);

                if (enableCancel && updateStatus == ProgressBarStatus.UserCancelled)
                {
                    break;
                }

                counter++;

                action(item);
            };

            preactorObjectModel.Preactor.DestroyStatus();
        }

        public static void Run<T>(PreactorObjectModel preactorObjectModel, IEnumerable<T> enumerable, Action action, string title, string message, bool enableCancel=false)
        {
            preactorObjectModel.Preactor.DisplayStatus(title, message);

            int counter = 1;
            int totalCount = enumerable.Count();

            foreach (var item in enumerable)
            {
                var updateStatus = preactorObjectModel.Preactor.UpdateStatus(counter, totalCount);

                if (enableCancel && updateStatus == ProgressBarStatus.UserCancelled)
                {
                    break;
                }

                counter++;

                action.Invoke();
            };

            preactorObjectModel.Preactor.DestroyStatus();
        }
    }
}
